package orange.com.openstack.sahara.httpConnection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import orange.com.openstack.sahara.Client;

/**
 * @author osvaldo.cocucci@gmail.com
 * 
 */
public class RestCall {

	public HttpURLConnection connection;

	/**
	 * @param connection
	 *            this method will interpret the connection returned message
	 * @return the connection message as a string
	 */
	public String getResponse(HttpURLConnection connection) {
		try {
			if (connection.getResponseCode() == 200 || connection.getResponseCode() == 202 || connection.getResponseCode() == 204) {
				String line;
				StringBuffer jsonString = new StringBuffer();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				try {
					while ((line = br.readLine()) != null) {
						jsonString.append(line);
					}

					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return (jsonString.toString());
			} else
				Client.logger.error(connection.getResponseCode() + " => "
						+ connection.getResponseMessage());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ("unknown error encountered");

	}

	/**
	 * @param urlPath
	 * @param payload
	 * @param POSTorGET
	 * 
	 *            method to do http connection. the payload can be null
	 * @return the connection element with response code and message
	 */
	public HttpURLConnection connect(String urlPath, String payload,
			String POSTorGET, String token) {
		try {
			URL url = new URL(urlPath);
			connection = (HttpURLConnection) url.openConnection();

			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setRequestMethod(POSTorGET);
			connection.setRequestProperty("Accept", "application/json");
			if (token != null)
				connection.setRequestProperty("X-Auth-Token", token);
			connection.setRequestProperty("Content-Type",
					"application/json; charset=UTF-8");
			if (payload != null) {
				OutputStreamWriter writer = new OutputStreamWriter(
						connection.getOutputStream(), "UTF-8");
				writer.write(payload);
				writer.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return connection;
	}

	public void disconnect() {
		if (connection != null)
			connection.disconnect();
	}
}
